package com.bkgy.controller.tcoilslit.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bkgy.commom.model.QueryDTO;
import com.bkgy.controller.tcoilslit.dto.TCoilSlitDto;
import com.bkgy.controller.tcoilslit.dto.TCoilSlitReportDto;
import com.bkgy.controller.tcoilslit.entity.TCoilSlit;
import com.bkgy.controller.tcoilslit.entity.TCoilSlitReport;
import com.bkgy.controller.tcoilslit.mapper.TCoilSlitMapper;
import com.bkgy.controller.tcoilslit.service.TCoilSlitService;
import com.bkgy.sys.common.entity.ResultData;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author dell
 * @description 针对表【T_COIL_SLIT(钢卷分切过程记录表，用于生产质量追溯)】的数据库操作Service实现
 * @createDate 2025-05-14 20:42:53
 */
@Service
public class TCoilSlitServiceImpl extends ServiceImpl<TCoilSlitMapper, TCoilSlit> implements TCoilSlitService {

    @Autowired
    private TCoilSlitMapper tCoilSlitMapper;

    // 定义数据库时间格式
    private static final DateTimeFormatter DB_DATE_TIME_FORMAT =
            DateTimeFormatter.ofPattern("yyyy-MM-dd-HH.mm.ss.SSSSSS");

    @Override
    public ResultData<Page<TCoilSlit>> findTCoilByPage(QueryDTO<TCoilSlitDto> queryDTO) {
        TCoilSlitDto dto = queryDTO.getDto();
        LambdaQueryWrapper<TCoilSlit> wrapper = new LambdaQueryWrapper<>();
        // 构建查询条件
        if (dto != null) {
            wrapper.like(StringUtils.hasText(dto.getProductLine()), TCoilSlit::getProductLine, dto.getProductLine());
            wrapper.like(StringUtils.hasText(dto.getOrderNo()), TCoilSlit::getOrderNo, dto.getOrderNo());
            wrapper.like(StringUtils.hasText(dto.getEntId()), TCoilSlit::getEntId, dto.getEntId());
            wrapper.like(StringUtils.hasText(dto.getSteelGrade()), TCoilSlit::getSteelGrade, dto.getSteelGrade());
        }
        wrapper.orderByDesc(TCoilSlit::getCreateTime);
        Page<TCoilSlit> page = new Page<>(queryDTO.getPage().getPageIndex(), queryDTO.getPage().getPageSize());
        Page<TCoilSlit> result = page(page, wrapper);
        return ResultData.ResultDataSuccess(result, (int) result.getTotal());
    }

    @Override
    public ResultData<TCoilSlitReportDto> getAggregatedData(String timeType, LocalDate date) {
        // 计算时间范围
        LocalDateTime startTime = getStartTime(timeType, date);
        LocalDateTime endTime = getEndTime(timeType, date);
        String stime = startTime.format(DB_DATE_TIME_FORMAT);//转为数据库格式，方便数据查询
        String etime = endTime.format(DB_DATE_TIME_FORMAT);
        // 查询所有维度数据 钢种 品规 班组 缺陷原因
        List<TCoilSlitReport> results = tCoilSlitMapper.getAggregatedData(stime, etime);

        // 按维度类型分组
        Map<String, List<TCoilSlitReport>> groupedResults = results.stream()
                .collect(Collectors.groupingBy(TCoilSlitReport::getDimensionType));

        // 构建响应对象
        TCoilSlitReportDto response = new TCoilSlitReportDto();
        response.setSteelGradeList(groupedResults.getOrDefault("STEEL_GRADE", Collections.emptyList()));
        response.setSpecList(groupedResults.getOrDefault("SPEC", Collections.emptyList()));
        response.setDefectList(groupedResults.getOrDefault("DEFECT_REASON", Collections.emptyList()));
        response.setTeamList(groupedResults.getOrDefault("CREW", Collections.emptyList()));

        return ResultData.ResultDataSuccess(response);
    }


    /**
     * 根据时间类型计算开始时间
     */
    private LocalDateTime getStartTime(String timeType, LocalDate date) {
        if (TimeType.DAY.getValue().equals(timeType)) {
            return LocalDateTime.of(date, LocalTime.MIN);
        } else if (TimeType.WEEK.getValue().equals(timeType)) {
            return LocalDateTime.of(date.with(DayOfWeek.MONDAY), LocalTime.MIN);
        } else if (TimeType.MONTH.getValue().equals(timeType)) {
            return LocalDateTime.of(date.withDayOfMonth(1), LocalTime.MIN);
        }
        throw new IllegalArgumentException("不支持的时间类型：" + timeType);
    }

    /**
     * 根据时间类型计算结束时间
     */
    private LocalDateTime getEndTime(String timeType, LocalDate date) {
        if (TimeType.DAY.getValue().equals(timeType)) {
            return LocalDateTime.of(date, LocalTime.MAX);
        } else if (TimeType.WEEK.getValue().equals(timeType)) {
            return LocalDateTime.of(date.with(DayOfWeek.SUNDAY), LocalTime.MAX);
        } else if (TimeType.MONTH.getValue().equals(timeType)) {
            return LocalDateTime.of(date.withDayOfMonth(date.lengthOfMonth()), LocalTime.MAX);
        }
        throw new IllegalArgumentException("不支持的时间类型：" + timeType);
    }
}


@Getter
enum TimeType {

    DAY("0"),
    WEEK("1"),
    MONTH("2");

    private final String value;

    TimeType(String value) {
        this.value = value;
    }

}




